<template>
  <div>
    <div class="search-result">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <van-cell
          v-for="(article, index) in list"
          :key="index"
          :title="article.title"
        />
      </van-list>
    </div>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search.js'
// console.log(getSearchResult)
export default {
  name: 'SearchResult',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      list: [], // 搜索结果
      loading: false,
      finished: false,
      page: 1, // 页码值
      per_page: 10, // 每页的条数
      error: false, // 错误提示
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onLoad() {
      // 1.异步更新数据

      try {
        const { data } = await getSearchResult({
          page: this.page,
          per_page: this.per_page,
          q: this.searchText,
        })
        // console.log(data)
        const { results } = data.data
        // 2.追加到list数组
        this.list.push(...results)
        // 3.关闭加载状态
        this.loading = false
        // 4.判断是否加载完成
        if (results.length === 0) {
          // 4.1如果已经完成，把finished设为true
          this.finished = true
        } else {
          // 4.2没有完成 页码加1
          this.page++
        }
      } catch (err) {
        //   vant -list组件的失败提示
        this.error = true
        this.loading = false
      }
    },
  },
}
</script>

<style lang="less" scoped></style>
